import axios from "axios";
import store from "@/store";
import router from "@/router";
import { Message, MessageBox } from "element-ui";
import { Notify, Dialog } from "vant";
import { getAdminToken, getAdminUserId, getAgent } from "@/utils/auth";

// 创建axios实例
const service = axios.create({
  baseURL:
    process.env.NODE_ENV === "development"
      ? process.env.VUE_APP_BASE_API
      : window.location.href.slice(0, window.location.href.indexOf("/user")), // 接口地址
  // withCredentials: true, // 跨域请求时发送Cookie
  timeout: 60000, // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 发送请求之前
    if (store.getters.adminToken && store.getters.adminToken != "undefined") {
      // 让每个请求头部带上AdminToken、AdminUserId
      config.headers["MemberToken"] =
        getAdminToken() != "undefined" ? getAdminToken() : "";
      config.headers["MemberId"] =
        getAdminUserId() != "undefined" ? getAdminUserId() : "";
    }
    return config;
  },
  (error) => {
    // 请求错误
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  /**
   * 通过接口返回码确定返回状态
   * 还可以通过HTTP状态代码来判断请求状态
   */
  (response) => {
    // 响应数据
    const res = response.data;

    // 返回码200：成功
    if (res.code === 200 || res.code == 210) {
      return res;
    } else {
      // 返回码401：AdminToken无效
      if (Boolean(Number(getAgent()))) {
        if (res.code === 401) {
          Dialog.alert({
            message: res.msg || "登录失效,重新登录",
            confirmButtonText: "重新登录",
          })
            .then(() => {
              setTimeout(() => {
                store.dispatch("user/resetAdminToken").then(() => {
                  location.reload();
                });
              }, 1000);
            })
            .catch(() => {});
        } else {
          if (response.config.url.indexOf("/cancelcollect") == -1) {
            if (res.msg != "验证失败") {
              Notify({
                message: res.msg || "请稍后再试",
                color: "#ff4949",
                background: "#ffdbdb",
              });
            }
          }
        }
      } else {
        if (res.code === 401) {
          MessageBox.confirm(res.msg, "提示", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              store.dispatch("user/resetAdminToken").then(() => {
                location.reload();
              });
            })
            .catch(() => {});
        } else {
          // console.log(res.return_msg!='OK','678');
          if (res.return_msg) {
            //微信端返回数据中没有code
            if (res.return_msg != "OK") {
              Message({
                message: res.return_msg || "服务器错误",
                type: "error",
                duration: 2000,
              });
            }
          } else if (
            res.msg != "验证失败" &&
            response.config.url.indexOf("/cancelcollect") == -1
          ) {
            Message({
              message: res.msg || "服务器错误",
              type: "error",
              duration: 2000,
            });
          }
        }
      }

      return res;
    }
  },
  (error) => {
    // 响应错误
    let err = error.response.data;
    // 返回码401：AdminToken无效
    // console.clear()
    if (!Boolean(Number(getAgent()))) {
      if (err.code == 401) {
        if (router.currentRoute.path != "/login") {
          store.dispatch("user/resetAdminToken").then(() => {
            location.reload();
          });
        }
      }
      if (error.config.url.indexOf("/chapter") == -1) {
        Message({
          message: err.message,
          type: "error",
          duration: 2000,
        });
      }
    } else {
      if (err.code === 401) {
        Dialog.alert({
          message: err.msg,
          confirmButtonText: "重新登录",
        })
          .then(() => {
            store.dispatch("user/resetAdminToken").then(() => {
              location.reload();
            });
          })
          .catch(() => {
            store.dispatch("user/resetAdminToken").then(() => {
              location.reload();
            });
          });
      }
    }
    return Promise.reject(err);
  }
);

export default service;
